<template>
  <div class="table-demo">
    <ElTableWrapper
      ref="tableRef"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.limit"
      :data="tableData"
      :columns="columns"
      :loading="loading"
      :total="total"
      :show-selection="true"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
      @refresh="fetchData"
    >
      <!-- 工具栏左侧插槽 -->
      <template #toolbar-left>
        <el-button
          type="primary"
          @click="handleAdd"
          >{{ $t('tableDemo.leftToolsBar.add') }}</el-button
        >
        <el-button
          type="danger"
          @click="handleBatchDelete"
          >{{ $t('tableDemo.leftToolsBar.deleteBatch') }}</el-button
        >
      </template>

      <!-- 状态列自定义插槽 -->
      <template #status="{ row }">
        <el-tag :type="row.status ? 'success' : 'danger'">
          {{ row.status ? $t('tableDemo.statusC.enable') : $t('tableDemo.statusC.disable') }}
        </el-tag>
      </template>

      <!-- 操作列插槽 -->
      <template #action="{ row }">
        <el-button
          link
          type="primary"
          @click="handleEdit(row)"
          >{{ $t('tableDemo.operationC.edit') }}</el-button
        >
        <el-button
          link
          type="danger"
          @click="handleDelete(row)"
          >{{ $t('tableDemo.operationC.delete') }}</el-button
        >
      </template>
    </ElTableWrapper>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { TableColumn, TableItem } from '../../../types/ui/elTableWrapper.ts'

  // 查询参数
  const queryParams = reactive({
    page: 1,
    limit: 10,
  })

  // 表格实例
  const tableRef = ref()

  // 表格数据
  const tableData = ref<TableItem[]>([])
  const total = ref(0)
  const loading = ref(false)
  const selectedRows = ref<TableItem[]>([])

  // 列配置
  const columns: TableColumn[] = [
    {
      label: 'tableDemo.usernameC',
      prop: 'username',
      minWidth: 120,
      sortable: 'custom',
    },
    {
      label: 'tableDemo.nameC',
      prop: 'name',
      minWidth: 120,
    },
    {
      label: 'tableDemo.phoneC',
      prop: 'phone',
      minWidth: 120,
    },
    {
      label: 'tableDemo.emailC',
      prop: 'email',
      minWidth: 180,
      showOverflowTooltip: true,
    },
    {
      label: 'tableDemo.statusC.label',
      prop: 'status',
      width: 100,
      slot: 'status',
    },
    {
      label: 'tableDemo.createTimeC',
      prop: 'createTime',
      minWidth: 180,
      sortable: 'custom',
    },
  ]

  // 获取表格数据
  const fetchData = async () => {
    loading.value = true
    try {
      // 模拟接口请求
      await new Promise(resolve => setTimeout(resolve, 500))

      // 生成模拟数据
      const mockData = Array.from({ length: queryParams.limit }).map((_, index) => {
        const id = (queryParams.page - 1) * queryParams.limit + index + 1
        return {
          id,
          username: `user${id}`,
          name: `用户${id}`,
          phone: '13800138000',
          email: `user${id}@example.com`,
          status: Math.random() > 0.5,
          createTime: new Date().toLocaleString(),
        }
      })

      tableData.value = mockData
      total.value = 100
    } finally {
      loading.value = false
    }
  }

  // 处理多选变化
  const handleSelectionChange = (selection: TableItem[]) => {
    selectedRows.value = selection
  }

  // 处理排序变化
  const handleSortChange = ({ prop, order }: { prop: string; order: string }) => {
    console.log('排序变化：', prop, order)
    fetchData()
  }

  // 处理新增
  const handleAdd = () => {
    ElMessage.success('点击了新增按钮')
  }

  // 处理编辑
  const handleEdit = (row: TableItem) => {
    ElMessage.success(`点击了编辑按钮，编辑的行ID为：${row.id}`)
  }

  // 处理删除
  const handleDelete = (row: TableItem) => {
    ElMessageBox.confirm('确认删除该记录吗？', '提示', {
      type: 'warning',
    }).then(() => {
      ElMessage.success(`删除成功，删除的行ID为：${row.id}`)
    })
  }

  // 处理批量删除
  const handleBatchDelete = () => {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请选择要删除的记录')
      return
    }

    ElMessageBox.confirm('确认删除选中的记录吗？', '提示', {
      type: 'warning',
    }).then(() => {
      const ids = selectedRows.value.map(row => row.id)
      ElMessage.success(`批量删除成功，删除的行ID为：${ids.join(',')}`)
      // 清空选中状态
      if (tableRef.value) {
        tableRef.value.clearSelection()
      }
    })
  }

  // 初始化
  onMounted(() => {
    fetchData()
  })
</script>

<style lang="scss" scoped>
  .table-demo {
    margin: 16px;
  }
</style>
